<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */

namespace app\command\kuaishou;

use app\command\BaseWork;
use app\enum\ConfigEnum;
use app\enum\KuaiShouEnum;
use app\service\batch\KuaiShouBatchService;
use app\service\fetch\KuaiShouFetchService;
use think\console\Input;
use think\console\Output;
use think\facade\Cache;

class KsActionSyncWork extends BaseWork
{
    public const REDIS_TASK_KEY = ConfigEnum::CACHE_CONFIG[KuaiShouEnum::BATCH_CONFIG_KEY]['action_bar_sync'];

    protected function configure()
    {
        // 指令配置
        $this->setName('ks_action_sync_work');
        $this->setDescription('同步快手行动号召按钮列表');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $this->getOutputMessage('同步快手行动号召按钮列表开始');

        $redis = Cache::store('redis')->handler();
        $st = time() + 5 * 60;
        while (time() < $st) {
            try {
                $str = $redis->lPop(self::REDIS_TASK_KEY);
                if (! $str) {
                    usleep(500000);
                    continue;
                }
                $arr = explode('|', $str);
                $advertiserId = strval($arr[0]);
                $version = intval($arr[1]);
                if (! $advertiserId) {
                    usleep(500000);
                    continue;
                }
                $res = KuaiShouBatchService::batchActionSync($advertiserId, $version);
                if (! $res) {
                    $this->getOutputMessage('同步快手行动号召按钮列表失败,账户id:' . $advertiserId . KuaiShouFetchService::getError(0));
                }
            } catch (\Exception $e) {
                $this->getOutputMessage('同步快手行动号召按钮列表失败' . $e->getMessage());
            }
        }
        $this->getOutputMessage('同步快手行动号召按钮列表结束');
    }
}
